import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 利用两个线程交替打印1-100
 * @Author：徐志荣
 * @Date：2023/9/2 上午 11:00
 */
public class Day0902 {
    static volatile int num = 0;
    static Object lock =new Object();
    public static void main(String[] args) {
        Runnable task1 = new Task1();
        Runnable task2 = new Task2();
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.execute(task1);
        pool.execute(task2);
    }
    static class Task1 implements Runnable{

        @Override
        public void run() {
            while (num<100){
                synchronized (lock){
                    //获取到锁
                    //使用while 避免 虚假唤醒
                    while (num%2 == 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //符合条件了，执行自己的逻辑
                    System.out.println(Thread.currentThread().getName() + ":"+num++);
                    lock.notifyAll();
                }
            }
        }
    }
   static class Task2 implements Runnable{

        @Override
        public void run() {
            while (num<100){
                synchronized (lock){
                    //获取到锁
                    //使用while 避免 虚假唤醒
                    while (num%2 == 1){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //符合条件了，执行自己的逻辑
                    System.out.println(Thread.currentThread().getName() + ":"+num++);
                    lock.notifyAll();
                }
            }
        }
        }
    }

